<script lang="ts" setup>
import { ref, defineProps, defineEmits, onMounted, watch, nextTick, computed } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import dayjs from "dayjs"
import { onClickOutside } from "@vueuse/core"
import { useSettingsStore } from "@/store/modules/settings"
import { useUserStore } from "@/store/modules/user"
import { useRouter } from "vue-router"
import { ChatDotRound, Edit, Location, Star, Check, CircleCloseFilled } from "@element-plus/icons-vue"

// 类型定义
interface CommentFormData {
  nickname: string
  content: string
  ip?: string
  time?: string
  articleID?: string
  trendsID?: string
}

interface CommentItem {
  _id: string
  nickname: string
  content: string
  time: string
  ip?: string
  address?: string
  avatar?: string
  likes?: number
  isLiked?: boolean
}

interface PageData {
  page: number
  pageSize: number
  total: number
}

// Props
const props = defineProps<{
  articleId: string
  articleType?: 'article' | 'community' | 'trends'
  province?: any[]
  status?: 'admin' | 'web'
  showEmoji?: boolean
  showLocation?: boolean
  // 新增：支持外部传入评论数据
  comments?: CommentItem[]
  total?: number
  loading?: boolean
  submitting?: boolean
  // 新增：是否显示折叠面板
  showCollapse?: boolean
}>()

// Emits
const emit = defineEmits(["update", "commentAdded", "submitComment", "getCommentList"])

// Store
const settingsStore = useSettingsStore()
const userStore = useUserStore()
const router = useRouter()

// 计算属性：是否已登录管理后台
const isLoggedIn = computed(() => {
  return !!userStore.token && !!userStore.userInfo
})

// 计算属性：当前用户昵称
const currentUserNickname = computed(() => {
  return userStore.userInfo?.nickname || '未知用户'
})

// 折叠面板显示
const activeNames = ref<number[]>([])

// 评论表单
const commentForm = ref<CommentFormData>({
  nickname: "", // 将自动设置为当前登录用户的昵称
  content: "",
  ip: "",
  time: "",
  articleID: props.articleId
})

// 检查登录状态并处理评论提交
const checkLoginAndSubmit = async () => {
  if (!isLoggedIn.value) {
    // 未登录，显示选择弹窗
    try {
      const result = await ElMessageBox.confirm(
        '您需要登录管理后台才能发表评论，是否前往登录？',
        '登录提示',
        {
          confirmButtonText: '去登录',
          cancelButtonText: '取消',
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (result === 'confirm') {
        router.push('/login')
      }
    } catch (error) {
      // 用户取消登录
      ElMessage.info('已取消评论')
    }
    return
  }

  // 已登录，直接提交评论
  await submitComment()
}

// 发布评论
const submitComment = async () => {
  // 校验输入信息
  if (commentForm.value.content === "") {
    return ElMessage.error("请输入评论内容")
  }

  // 自动设置用户信息
  commentForm.value.nickname = currentUserNickname.value
  commentForm.value.time = dayjs(Date.now()).format("YYYY-MM-DD HH:mm")

  // 通过自定义事件发送评论数据给父组件处理
  emit("submitComment", {
    ...commentForm.value,
    articleType: props.articleType,
    status: props.status
  })
}

// 清除评论
const clearComment = () => {
  commentForm.value.nickname = ""
  commentForm.value.content = ""
  commentForm.value.ip = ""
  commentForm.value.time = ""
}

// 列表加载
const loading = ref<boolean>(false)

// 获取评论列表
const getCommentList = async () => {
  loading.value = true
  try {
    // 通过自定义事件请求父组件获取评论列表
    emit("getCommentList", {
      articleId: props.articleId,
      articleType: props.articleType,
      page: pageData.value.page,
      pageSize: pageData.value.pageSize
    })
  } catch (error) {
    loading.value = false
  }
}

// 处理评论发布成功
const handleCommentSubmitSuccess = () => {
  clearComment()
  getCommentList()
  emit("commentAdded")
}

// 处理评论发布失败
const handleCommentSubmitError = (error: any) => {
  ElMessage.error("评论失败")
  console.error("评论发布失败:", error)
}

// 处理评论列表数据
const handleCommentListData = (data: any) => {
  if (data && data.comments) {
    commentList.value = commentList.value.concat(data.comments)
    pageData.value.total = data.total || 0
  }
  loading.value = false
}

// 删除评论
const delComment = async (id: string) => {
  ElMessageBox.confirm("确定删除该评论吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      // 这里需要调用删除API
      ElMessage.success("删除成功")
      await getCommentList()
      emit("update", -1)
    } catch (error) {
      ElMessage.error("删除失败")
    }
  })
}

// 分页数据
const pageData = ref<PageData>({
  page: 1,
  pageSize: 5,
  total: 0
})

// 加载更多
const loadMore = async () => {
  if (commentList.value.length < pageData.value.total) {
    pageData.value.page++
    await getCommentList()
  }
  if (commentList.value.length === pageData.value.total) {
    ElMessage.success("加载完毕")
  }
}

// 分页处理
const handlePageChange = (page: number) => {
  pageData.value.page = page
  if (props.showCollapse) {
    getCommentList()
  } else {
    emit("getCommentList", {
      articleId: props.articleId,
      articleType: props.articleType,
      page: page,
      pageSize: pageData.value.pageSize
    })
  }
}

// 评论列表
const commentList = ref<CommentItem[]>([])

// 表情选择
const selectedEmoji = ref<string>("")
const showEmoji = ref<boolean>(false)
const showEmojiPicker = ref<boolean>(false)

// 打开表情输入框
const openEmoji = () => {
  showEmoji.value = !showEmoji.value
}

// 选择表情
const selectEmoji = (emoji: any) => {
  commentForm.value.content += emoji.i
  selectedEmoji.value = ""
}

// 表情选择组件
const emojiPicker = ref<any>(null)

// 点击表情组件以外的位置，关闭表情选择框
onClickOutside(emojiPicker, () => {
  showEmoji.value = false
})

// 打开评论列表
const openComment = async () => {
  if (activeNames.value.length !== 0) {
    await getCommentList()
    if (props.showEmoji) {
      setTimeout(() => {
        showEmojiPicker.value = true
      }, 1000)
    }
  } else {
    showEmojiPicker.value = false
  }
}

// 监听文章ID变化
watch(() => props.articleId, () => {
  commentForm.value.articleID = props.articleId
})

onMounted(() => {
  // 初始化
})

// 暴露给父组件的方法
defineExpose({
  handleCommentSubmitSuccess,
  handleCommentSubmitError,
  handleCommentListData,
  getCommentList
})
</script>

<template>
  <div class="universal-comment">
    <!-- 折叠模式 -->
    <el-collapse v-if="showCollapse" @change="openComment" v-model="activeNames">
      <el-collapse-item title="评论区" :name="1">
        <!-- 评论输入区域 -->
        <div class="comment-input-section">
          <!-- 显示当前登录用户信息 -->
          <div v-if="isLoggedIn" class="user-info-display">
            <el-tag type="success" size="small">
              <el-icon><Check /></el-icon>
              当前用户：{{ currentUserNickname }}
            </el-tag>
          </div>

          <div v-else class="login-prompt">
            <el-tag type="warning" size="small">
              <el-icon><CircleCloseFilled /></el-icon>
              请先登录管理后台才能发表评论
            </el-tag>
          </div>

          <el-row v-if="showLocation && province">
            <el-select v-model="commentForm.ip" placeholder="请选择省份" style="width: 150px; margin-bottom: 10px">
              <el-option v-for="item in province" :key="item" :label="item.name" :value="item.name" />
            </el-select>
          </el-row>

          <el-input
            type="textarea"
            placeholder="期待能留下足迹~~ ✨ ✨ ✨"
            maxlength="100"
            show-word-limit
            v-model="commentForm.content"
            :rows="3"
          />

          <el-row align="middle" style="position: relative">
            <el-button
              class="comment-submit-btn"
              style="margin: 10px 0 0 0"
              type="primary"
              size="small"
              @click="checkLoginAndSubmit"
              :disabled="!isLoggedIn"
              :loading="submitting"
            >
              {{ isLoggedIn ? '发布' : '请先登录' }}
            </el-button>

            <SvgIcon
              v-if="showEmoji"
              @click="openEmoji"
              style="width: 25px; height: 25px; margin-top: 10px; margin-left: 10px"
              name="emoji"
              :style="{ color: showEmoji ? '#3cbff5' : '#666' }"
            />

            <Vue3EmojiPicker
              v-if="showEmojiPicker && showEmoji"
              ref="emojiPicker"
              class="emoji"
              :class="{ active: showEmoji }"
              :native="true"
              @select="selectEmoji"
              v-model="selectedEmoji"
            />
          </el-row>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list" v-loading="loading">
          <div v-if="commentList.length === 0 && !loading" class="empty-state">
            <el-icon class="empty-icon"><ChatDotRound /></el-icon>
            <p class="empty-text">暂无评论，快来抢沙发吧~</p>
          </div>

          <div v-else class="comment-items">
            <ul class="list">
              <li
                v-for="item in commentList"
                :key="item._id"
                class="item"
              >
                <div class="info">
                  <span class="name">{{ item.nickname || '匿名用户' }}</span>
                  <span class="ip" v-if="item.address || item.ip">
                    <i>IP:{{ item.address || item.ip }}</i>
                  </span>
                  <span class="time">{{ item.time }}</span>
                </div>

                <div class="content">{{ item.content }}</div>
                <div class="del">
                  <el-icon v-if="props.status === 'web'" :size="20">
                    <ChatDotRound />
                  </el-icon>
                  <el-icon
                    v-else
                    @click="delComment(item._id)"
                    :size="20"
                    color="#E73037"
                  >
                    <CircleCloseFilled />
                  </el-icon>
                </div>
              </li>
            </ul>
          </div>

          <!-- 加载更多 -->
          <div class="load-more-section">
            <el-button
              v-if="commentList.length < pageData.total"
              class="load-more-btn"
              @click="loadMore"
              :loading="loading"
            >
              加载更多评论
            </el-button>
            <div v-else-if="commentList.length > 0" class="no-more">
              <el-icon><Check /></el-icon>
              已显示全部评论
            </div>
          </div>
        </div>
      </el-collapse-item>
    </el-collapse>

    <!-- 直接显示模式 -->
    <div v-else class="comment-section">
      <div class="comment-header">
        <h3>评论区 ({{ total || pageData.total }})</h3>
      </div>

      <!-- 评论输入区域 -->
      <div class="comment-input-wrapper">
        <!-- 显示当前登录用户信息 -->
        <div v-if="isLoggedIn" class="user-info-display">
          <el-tag type="success" size="small">
            <el-icon><Check /></el-icon>
            当前用户：{{ currentUserNickname }}
          </el-tag>
        </div>

        <div v-else class="login-prompt">
          <el-tag type="warning" size="small">
            <el-icon><CircleCloseFilled /></el-icon>
            请先登录管理后台才能发表评论
          </el-tag>
        </div>

        <el-select
          v-if="showLocation && province"
          v-model="commentForm.ip"
          placeholder="选择地区"
          style="width: 150px; margin-bottom: 10px"
          clearable
        >
          <el-option v-for="item in province" :key="item" :label="item.name" :value="item.name" />
        </el-select>
        <el-input
          v-model="commentForm.content"
          type="textarea"
          placeholder="说点什么吧..."
          :rows="3"
          maxlength="500"
          show-word-limit
          style="margin-top: 10px"
        />
        <div class="comment-actions">
          <el-button
            class="comment-submit-btn"
            type="primary"
            size="small"
            @click="checkLoginAndSubmit"
            :loading="submitting"
            :disabled="!isLoggedIn"
          >
            {{ isLoggedIn ? '发表评论' : '请先登录' }}
          </el-button>
        </div>
      </div>

      <!-- 评论列表 -->
      <div v-loading="loading" class="comment-list">
        <el-empty v-if="(comments || commentList).length === 0 && !loading" description="暂无评论，快来抢沙发！" />

        <div v-else class="comment-items">
          <ul class="list">
            <li
              v-for="item in (comments || commentList)"
              :key="item._id"
              class="item"
            >
              <div class="info">
                <span class="name">{{ item.nickname || '匿名用户' }}</span>
                <span class="ip" v-if="item.address || item.ip">
                  <i>IP:{{ item.address || item.ip }}</i>
                </span>
                <span class="time">{{ item.time }}</span>
              </div>

              <div class="content">{{ item.content }}</div>
              <div class="del">
                <el-icon v-if="props.status === 'web'" :size="20">
                  <ChatDotRound />
                </el-icon>
                <el-icon
                  v-else
                  @click="delComment(item._id)"
                  :size="20"
                  color="#E73037"
                >
                  <CircleCloseFilled />
                </el-icon>
              </div>
            </li>
          </ul>
        </div>

        <!-- 分页 -->
        <div v-if="(total || pageData.total) > pageData.pageSize" class="comment-pagination">
          <el-pagination
            small
            background
            layout="prev, pager, next"
            :total="total || pageData.total"
            :page-size="pageData.pageSize"
            :current-page="pageData.page"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.universal-comment {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-top: 20px;

  .comment-input-section {
    padding: 20px;
    background: #fafafa;
    border-bottom: 1px solid #f0f0f0;
  }

  .comment-list {
    padding: 0;

    .empty-state {
      text-align: center;
      padding: 60px 24px;
      color: #999;

      .empty-icon {
        font-size: 48px;
        color: #ddd;
        margin-bottom: 16px;
      }

      .empty-text {
        font-size: 16px;
        color: #999;
        margin: 0;
      }
    }

    .comment-items {
      .list {
        width: 100%;
        padding: 10px;
        display: flex;
        flex-direction: column;
        align-items: center;
        list-style: none;

        .item {
          width: 100%;
          padding: 10px 0;
          border-bottom: 1px solid #efefef;
          position: relative;

          .info {
            .name {
              font-size: 0.7em;
              font-weight: 600;
            }
            .ip {
              font-size: 0.6em;
              color: #999;
              margin-left: 10px;
            }
            .time {
              font-size: 0.6em;
              color: #999;
              margin-left: 10px;
              float: right;
            }
          }

          .content {
            margin: 8px 0;
            font-size: 14px;
            line-height: 1.5;
            color: #333;
            word-break: break-word;
          }

          .del {
            position: absolute;
            width: 100%;
            height: 100%;
            left: 0;
            top: 0;
            background-color: rgba(0, 0, 0, 0.03);
            clip-path: circle(0% at 95% 70%);
            transition: all 0.7s;
            border-radius: 10px;
            cursor: pointer;

            .el-icon {
              position: absolute;
              right: 3%;
              bottom: 15%;
              transform: scale(0);
              transition: all 0.6s;
            }
          }

          &:hover {
            .del {
              clip-path: circle(200% at 95% 70%);
              .el-icon {
                transform: scale(1);
              }
            }
          }
        }
      }
    }

    .load-more-section {
      padding: 20px 24px;
      text-align: center;
      border-top: 1px solid #f0f0f0;

      .load-more-btn {
        background: var(--gradient-primary);
        border: none;
        color: white;
        font-weight: 500;
        padding: 12px 32px;
        border-radius: 25px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }
      }

      .no-more {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        color: #999;
        font-size: 14px;
        padding: 20px 0;

        .el-icon {
          color: #67c23a;
        }
      }
    }
  }

  // 直接显示模式样式
  .comment-section {
    padding: 20px;
  }

  .comment-header {
    margin-bottom: 20px;

    h3 {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }

  .comment-input-wrapper {
    background: #f7f8fa;
    padding: 15px;
    border-radius: 8px;
    margin-bottom: 20px;

    .comment-actions {
      display: flex;
      justify-content: flex-end;
      gap: 10px;
      margin-top: 10px;
    }
  }

  .comment-list {
    min-height: 200px;
  }

  .comment-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  // 用户信息显示样式
  .user-info-display {
    margin-bottom: 10px;

    .el-tag {
      font-size: 12px;
      padding: 4px 8px;
    }
  }

  .login-prompt {
    margin-bottom: 10px;

    .el-tag {
      font-size: 12px;
      padding: 4px 8px;
    }
  }

  // 评论提交按钮样式优化
  .comment-submit-btn {
    min-width: 80px;
    font-weight: 500;
    border-radius: 6px;
    transition: all 0.3s ease;

    &.is-disabled {
      opacity: 0.6;
      cursor: not-allowed;
      background-color: #c0c4cc;
      border-color: #c0c4cc;
      color: #ffffff;
    }

    &:not(.is-disabled) {
      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }

      &:active {
        transform: translateY(0);
      }
    }

    &.is-loading {
      opacity: 0.8;
    }
  }
}

.emoji {
  position: absolute;
  z-index: 1000;
  right: 0px;
  top: 0px;
  transform: scale(0);
  transition: all 0.3s;
  &.active {
    transform: scale(1);
  }
}

::v-deep(.el-collapse-item__wrap) {
  overflow: visible;
}

// 响应式设计
@media (max-width: 768px) {
  .universal-comment {
    margin: 16px -16px 0;
    border-radius: 0;

    .comment-input-section {
      padding: 16px 20px;
    }

    .comment-list {
      .comment-items {
        .comment-item {
          padding: 16px 20px;

          .comment-avatar {
            margin-right: 12px;
          }

          .comment-content {
            .comment-meta {
              gap: 8px;
            }
          }
        }
      }

      .load-more-section {
        padding: 16px 20px;
      }
    }
  }
}
</style>
